"use strict";
import dayjs from 'dayjs';

/**
 * 日期格式化
 *
 * @param fmt 日期格式 例：yyyy-MM-dd hh:mm:ss
 */
Date.prototype.format = function (fmt) {
    var o = {
        "yyyy": this.getYear(), // 年
        "MM": this.getMonth() + 1, // 月份
        "dd": this.getDate(), // 日
        "hh": this.getHours(), // 小时
        "mm": this.getMinutes(), // 分
        "ss": this.getSeconds(), // 秒
        "q": Math.floor((this.getMonth() + 3) / 3), // 季度
        "S": this.getMilliseconds() // 毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

/**
 * 范围随机数
 *
 * @param from 随机数范围from
 * @param to 随机数范围to
 */
const $randomRange = (from, to) => {
    return Math.floor(Math.random() * (to - from) + from);
};

/**
 * 数值随机数
 *
 * @param length 长度
 */
const $randomNum = length => {
    let val;
    while ((val = Math.random()) < 0.1) {
        // 防止出现0.0X类型的随机数，导致结果位数不正确
    }
    return Math.floor(val * Math.pow(10, length));
};

/**
 * 数值格式化(千位逗号分隔)
 *
 * @param value 对象值
 * @param defaultZero 空时默认显示0
 */
const $formatNum = (value, defaultZero) => {
    if (!value) {
        if (defaultZero) {
            value = 0;
        } else {
            return "";
        }
    }
    let nums = value.toString().split("\.");
    let num = nums[0];
    let result = '';
    while (num.length > 3) {
        result = ',' + num.slice(-3) + result;
        num = num.slice(0, num.length - 3);
    }
    if (num) {
        result = num + result;
    }
    return result + (nums.length > 1 ? ("." + nums[1]) : "");
};

/**
 * 验证手机号
 * @param number
 * @returns {boolean}
 */
const $checkPhone = (number) => {
    if (!(/^1[3456789]\d{9}$/.test(number))) {
        return false
    }
    return true
}


/**
 * 日期格式化
 *
 */
const $formatDate = (time, second) => {
    var now = new Date;
    var that = new Date(time.replace(/-/g, '/'));
    if (that.getFullYear() == now.getFullYear() &&
        that.getMonth() == now.getMonth() &&
        that.getDate() == now.getDate() - 1) {
        return '昨天' + that.format('hh:mm' + (second ? ":ss" : ''));
    }
    if (that.getFullYear() == now.getFullYear() &&
        that.getMonth() == now.getMonth() &&
        that.getDate() == now.getDate()) {
        return that.format('hh:mm' + (second ? ":ss" : ''));
    }
    if (that.getFullYear() == now.getFullYear() &&
        that.getMonth() == now.getMonth() &&
        that.getDate() == now.getDate() - 2) {
        return '前天' + that.format('hh:mm' + (second ? ":ss" : ''));
    }

    if (that.getFullYear() == now.getFullYear() &&
        that.getMonth() == now.getMonth() &&
        that.getDate() != now.getDate()) {
        return that.format('MM-dd');
    }

    if (that.getFullYear() == now.getFullYear() &&
        that.getMonth() != now.getMonth()) {
        return that.format('MM-dd hh:mm' + (second ? ":ss" : ''));
    }

    if (that.getFullYear() != now.getFullYear()) {
        return that.format('yy-MM-dd hh:mm' + (second ? ":ss" : ''));
    }
    return that.format('yy-MM-dd hh:mm' + (second ? ":ss" : ''));
}

/**
 * 富文本转纯文本
 */
const $toText = (HTML) => {
    if (HTML) {
        return HTML.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi, '').replace(/<[^>]+?>/g, '').replace(/\s+/g,
            ' ').replace(/ /g, ' ').replace(/>/g, ' ');
    }
    return HTML
}

/**
 * 匹配方法
 *
 * @param text 正文
 * @param keyword 关键字
 * @param styleObj 自定义样式
 */
const $matchKeyword = (text, keyword, styleObj) => {
    if (!keyword || !text) return text;
    // 把匹配关键字中的正则符转义
    keyword = '(' + keyword.replace(/([\+\.\*\|\?\-\(\[\^\$])/g, '\\$1').replace(/\s+/g, '|') + ')';
    let reg = new RegExp(keyword, "igm");
    let style = "";
    if (styleObj) {
        for (let key in styleObj) {
            style += key + ": " + styleObj[key] + ";";
        }
    }
    return text.replace(reg, "<span style='" + (style || 'color:#ff0900') + "'>$1</span>")
};

/**
 * base64轉blob
 * @param dataurl
 * @returns {Blob}
 */
const $dataURLtoBlob = (dataurl) => {
    var arr = dataurl.split(',');
    //注意base64的最后面中括号和引号是不转译的
    var _arr = arr[1].substring(0, arr[1].length - 2);
    var mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(_arr),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
        type: mime
    });
}

/**
 * 金额格式化
 * @param money
 * @param num
 * @returns {number}
 */
const $formatMoney = (money, num = 2) => {
    return (parseFloat(money) / 100).toFixed(num)
}

/**
 * 根据生日计算年龄
 * @param strBirthday
 * @returns {number}
 */
const $getAgeByBirthday = (strBirthday) => {
    var returnAge;
    var strBirthdayArr = strBirthday.split('-');
    var birthYear = strBirthdayArr[0];
    var birthMonth = strBirthdayArr[1];
    var birthDay = strBirthdayArr[2];
    //获取当前日期
    var d = new Date();
    var nowYear = d.getFullYear();
    var nowMonth = d.getMonth() + 1;
    var nowDay = d.getDate();
    if (nowYear == birthYear) {
        returnAge = 0; //同年 则为0岁
    } else {
        var ageDiff = nowYear - birthYear; //年之差
        if (ageDiff > 0) {
            if (nowMonth == birthMonth) {
                var dayDiff = nowDay - birthDay; //日之差
                if (dayDiff < 0) {
                    returnAge = ageDiff - 1;
                } else {
                    returnAge = ageDiff;
                }
            } else {
                var monthDiff = nowMonth - birthMonth; //月之差
                if (monthDiff < 0) {
                    returnAge = ageDiff - 1;
                } else {
                    returnAge = ageDiff;
                }
            }
        } else {
            returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天
        }
    }
    return returnAge; //返回周岁年龄
}

/**
 * 金额格式化
 * @param money
 * @param num
 * @returns {number}
 */
const $textareaFormat = (html) => {
    return html.replace(/\n/g, '<br/>');
}

/**
 * 金额大写
 * @param n
 * @returns {string}
 */
const $digitUppercase = (n) => {
    var fraction = ['角', '分'];
    var digit = [
        '零', '壹', '贰', '叁', '肆',
        '伍', '陆', '柒', '捌', '玖'
    ];
    var unit = [
        ['元', '万', '亿'],
        ['', '拾', '佰', '仟']
    ];
    var head = n < 0 ? '欠' : '';
    n = Math.abs(n);
    var s = '';
    for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
    }
    s = s || '整';
    n = Math.floor(n);
    for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
    }
    return head + s.replace(/(零.)*零元/, '元')
        .replace(/(零.)+/g, '零')
        .replace(/^整$/, '零元整');
}

/**
 * 计算两个日期之间的小时差
 */
const $countHourByDate = (startTime) =>{
	if (!startTime) return 0
    var startTime = dayjs(startTime).format("YYYY-MM-DD HH:mm:ss")
    var endTime = dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")
    var regTime = /(\d{4})-(\d{1,2})-(\d{1,2})( \d{1,2}:\d{1,2})/g;
    var interval = Math.abs(Date.parse(startTime.replace(regTime, "$2-$3-$1$4")) - Date.parse(endTime.replace(regTime, "$2-$3-$1$4")))/1000;
    var h = Math.floor(interval / 3600);
    return h
}


export default {
    randomRange: $randomRange,
    randomNum: $randomNum,
    checkPhone: $checkPhone,
    formatDate: $formatDate,
    toText: $toText,
    matchKeyword: $matchKeyword,
    dataURLtoBlob: $dataURLtoBlob,
    formatMoney: $formatMoney,
    getAgeByBirthday: $getAgeByBirthday,
    textareaFormat: $textareaFormat,
    digitUppercase: $digitUppercase,
    countHourByDate: $countHourByDate
};
